//牛客 CM11 链表分割
//思路：1.创建两个使用带哨兵位的结构体指针，并为其开辟动态内存
//2.一个存放小于x的所有结点，一个存放大于x的所有结点
//3.将大头指针连接在小头指针尾部的next上，重点是要将大头指针的尾结点的next置空
//4.将小头指针的next赋给pHead，返回pHead

#include <stdlib.h>
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
class Partition {
public:
    ListNode* partition(ListNode* pHead, int x) {
        // write code here
        struct ListNode* lesshead = NULL, * lesstail = NULL, * greaterhead = NULL,
            * greatertail = NULL, * cur = pHead;
        lesshead = lesstail = (struct ListNode*)malloc(sizeof(struct ListNode));
        greaterhead = greatertail = (struct ListNode*)malloc(sizeof(struct ListNode));

        while (cur)
        {
            //尾插
            if (cur->val < x)
            {
                lesstail->next = cur;
                lesstail = lesstail->next;
            }
            else
            {
                greatertail->next = cur;
                greatertail = greatertail->next;
            }
            //迭代
            cur = cur->next;
        }

        //连接
        lesstail->next = greaterhead->next;
        //置空大头尾结点的next
        greatertail->next = NULL;
        //将新的头结点指针赋给原头结点指针
        pHead = lesshead->next;
        //释放大小头结点
        free(lesshead);
        free(greaterhead);

        return pHead;
    }
};